layui.define(['table','laydate','layer','form'],function(exports){ //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
    var $ = layui.$,
    table = layui.table,
    layer = layui.layer,
    element = layui.element,
    util = layui.util,
    form = layui.form,
    laydate = layui.laydate;
  	var optName,sourcepass='';
  	var tableObj = table.render({
  	  id: 'main-table',
  	  elem: '#table', //指定原始表格元素选择器（推荐id选择器）
  	  url: '/boss/download/aria-active',
  	  method:'post',
  	  autoSort : false,
  	  size: 'sm',
	  even: true,
  	  toolbar: '#toolbar',
  	  height: 'full-70',
      headers: {
        'Content-Type': 'application/json'
      },
  	  page: false,
  	  cols: [[
  		  {type:'checkbox'},
  		  {field: 'name', title: '文件摘要',sort:false,templet: function(d){
              if(d.files.length > 0){
                return d.files[0].path;
              } else {
                return '--';
              }
  	      }},
  		  {field: 'downloadSpeed', title: '下载速度',sort:false,width:100,templet: function(d){
  			  switch(d.downloadSpeed) {
                case 0:
                    return '0 k/s';
                case null:
                    return '空';
                case '':
                    return '--';
  			  	default:
  			  		return (d.downloadSpeed/1024).toFixed(2)+' k/s';
  			  }
  	      }},
  		  {field: 'totalLength', title: '文件大小',sort:false,width:100,templet: function(d){
  			  switch(d.totalLength) {
  			  	case null:
  			  		return '空';
  			  	case '':
  			  		return '--';
  			  	default:
  			  		return (d.totalLength/1024/1024).toFixed(2)+' M';
  			  }
  	      }},
  		  {field: 'completedLength', title: '完成进度',sort:false,width:100,templet: function(d){
              return '<div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="progressBar_' + d.id + '">' +
                                              '<div class="layui-progress-bar" lay-percent="' + d.progress + '"></div>' +
                                              '</div>';
  	      }},
  	      {field: 'connections', title: '连接数',sort:false,width:70,templet: function(d){
  			  switch(d.connections) {
  			  	case null:
  			  		return '空';
  			  	case '':
  			  		return '--';
  			  	default:
  			  		return d.connections;
  			  }
  	      }},
  		  {field: 'numSeeders', title: '种子数量',sort:false,width:70,templet: function(d){
  			  switch(d.numSeeders) {
  			  	case null:
  			  		return '空';
  			  	case '':
  			  		return '--';
  			  	default:
  			  		return d.numSeeders;
  			  }
  	      }},
  	      {field: 'uploadSpeed', title: '上传速度',sort:false,width:100,templet: function(d){
  			  switch(d.uploadSpeed) {
  			  	case null:
  			  		return '空';
  			  	case 0:
  			  		return '0';
  			  	case '':
  			  		return '--';
  			  	default:
  			  		return (d.uploadSpeed/1024).toFixed(2)+' k/s';
  			  }
  	      }},
  	      {field: 'uploadLength', title: '上传大小',sort:false,width:100,templet: function(d){
  			  switch(d.uploadLength) {
  			  	case null:
  			  		return '空';
  			  	case '':
  			  		return '--';
  			  	default:
  			  		return (d.uploadLength/1024/1024).toFixed(2)+'M';
  			  }
  	      }},
  		  {fixed: 'right', title:'操作', toolbar: '#optbar', width:165}
  	  ]],
  	  done: function(res, curr, count){
        res.data.forEach(function (item) {
            element.progress('progressBar_' + item.id, (item.completedLength/item.totalLength*100).toFixed(2) + '%');
            element.render();
        });
	  }
  	});
  	
  	/** 顶部toolbar事件 **/
  	table.on('toolbar(table)', function(obj){
  		switch(obj.event){
  		  case 'refresh-opt':
			    tableObj.reload();
			  break;
  		  case 'batch-del-opt':
  			  var checkStatus = table.checkStatus('main-table');
  			  if(checkStatus.data.length ==0){
  				  layer.alert('请先选择待删除行',{icon: 5});
  				  return;
  			  }
  			  layer.confirm("你确定批量删除"+checkStatus.data.length+"个项目吗？", {icon: 3, title:'提示'},
  			            function(index){//确定回调
      				  		var keys = new Array();
      				  		$.each(checkStatus.data,function(i,item){
      				  			keys.push(item.id);
      				  		});
      				  		batchDelete(keys,index);
  			            },function (index) {//取消回调
  			               layer.close(index);
  			            }
  			        );
  			  break;
  		}
  	});
  	/**
     * 主表单提交监听事件
     */
  	form.on('submit(add-download)', function(data){
	  $.ajax({
		    type: 'POST',
		    url: '/boss/download/download-file',
		    data: data.field,
		    success: function (data) {
		        if(data.success){
		        	layer.closeAll();
		        	tableObj.reload();
		        	layer.msg(data.message);
		        }else{
		            layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
		        }
		    },
		    error: function(data) {
		        layer.msg(data.responseJSON.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
		    },
		    dataType: "json"
		});
	  return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
	});
  	
  	/** 右侧tool事件 **/
  	table.on('tool(table)', function(obj){
  		var data = obj.data;
  		switch(obj.event){
  		  case 'edit-opt':
  			  optName = 'update';
  			  layer.open({
  				  type: 1,
  				  area: ['700px','350px'],
  				  title : '编辑',
  				  content: $('#windows'),
  				  shadeClose : false,
  				  move : false,
  				  btn : [ '确定', '取消' ],
  				  success : function(layero, index){
  					  $('#win-form')[0].reset();
  					  $.post(
  							  "/boss/boss_user/get_by_pk",
  							  {id:data.id},
  							  function(data, textStatus, jqXHR){
  								  form.val("win-form",data);
  							  },"json");
  					  sourcepass = data.password;
  				  },
				  yes : function(index, layero) {
					  $('#win-submit').trigger('click');
				  }
  				});
  			  break;
  		  case 'view-opt':
  			  optName = 'view';
  			  layer.open({
  				  type: 1,
  				  area: ['700px','350px'],
  				  title : '查看',
  				  content: $('#windows'),
  				  shadeClose : false,
  				  move : false,
  				  btn : [ '关闭'],
  				  success : function(layero, index){
  					  $('#win-form')[0].reset();
  					  $.post(
  							  "/boss/boss_user/get_by_pk",
  							  {id:data.id},
  							  function(data, textStatus, jqXHR){
  								  form.val("win-form",data);
  							  },"json");
  				  },
  				  btn1 : function(index, layero) {
  					  layer.closeAll();
				  }
  				});
  			  break;
  		  case 'del-opt':
  			  layer.confirm("你确定删除项目“"+obj.data.gid  +"”吗？", {icon: 3, title:'提示'},
			            function(index){//确定回调
    				  		var keys = new Array();
    				  		keys.push(obj.data.gid);
    				  		batchDelete(keys,index);
			            },function (index) {//取消回调
			               layer.close(index);
			            }
			        );
  			  break;
  		}
  	});
  	
  	form.on('submit(search-opt)',function(data){
  		tableObj.reload({where:data.field});
  	    return false;
  	});
  	
    util.on('lay-on', {
        'addData-opt': function(){
            layer.open({
            type: 1,
            offset: 'r',
            anim: 'slideLeft', // 从右往左
            area: ['600px', '100%'],
            shade: 0.1,
            shadeClose: true,
            id: 'addData-opt-layer-direction-r',
            content: $('#add-windows'),
            btn : [ '确定', '取消' ],
            success : function(layero, index){
                $('#win-form')[0].reset();
            },
            yes : function(index, layero) {
                $('#win-submit').trigger('click');
            }
        },
       );
      },
      'setting-opt': function(){
          layer.open({
          type: 1,
          offset: 'r',
          anim: 'slideLeft', // 从右往左
          area: ['600px', '100%'],
          shade: 0.1,
          shadeClose: true,
          id: 'addData-opt-layer-direction-r',
          content: $('#setting-windows'),
          btn : [ '确定', '取消' ],
          success : function(layero, index){
              $('#win-form')[0].reset();
          },
          yes : function(index, layero) {
              $('#win-submit').trigger('click');
          }
      },
     );
    }
    });
  	function batchDelete(keys,index){
  		$.ajax({
                type: 'POST',
                url: '/boss/download/force-remove',
                data: JSON.stringify(keys),
                success: function (data) {
                    if(data.success){
                        layer.close(index);
                    }else{
                        layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
                    }
                    tableObj.reload();
                    layer.msg(data.message);
                },
                error: function(data) {
                    layer.msg(data.responseJSON.message,{icon: 5,anim: 6,title:'错误',time: 0,btn:['确定']});
                },
                contentType: "application/json",
                dataType: "json"
            });
  	}
  //输出download接口
  exports('download', {});
});